﻿/**************************************************************
 * Copyright Eastmoney Corporation. All rights reserved.
 * 
 * Author: guitao(guitao@eastmoney.com) 
 * Create Date: 2020/10/26 14:12:09
 * Description:
 *          
 * Revision History:
 *      Date         Author               Description
 *              
***************************************************************/

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Quartz;
using Quartz.Spi;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace QuartzJob.Sample
{
    public class QuartzJobHostedService : IHostedService
    {
        private readonly IScheduler _scheduler;
        private readonly ILogger<QuartzJobHostedService> _logger;

        public QuartzJobHostedService(IScheduler scheduler,
            ILogger<QuartzJobHostedService> logger)
        {
            _scheduler = scheduler;
            _logger = logger;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            //just for sample test,should configuration in config file when dev
            //sample job 
            var job = CreateJob(typeof(SampleJob));
            var trigger = CreateTrigger("SampleJob", "0/5 * * * * ?");
            await _scheduler.ScheduleJob(job, trigger, cancellationToken);

            //disposed job
            var job2 = CreateJob(typeof(DisposedSampleJob));
            var trigger2 = CreateTrigger("DisposeSampleJob", "0/10 * * * * ?");
            await _scheduler.ScheduleJob(job2, trigger2, cancellationToken);

            await _scheduler.Start(cancellationToken);

            _logger.LogInformation("jobScheduler started.");
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            await _scheduler?.Shutdown(cancellationToken);

            _logger.LogInformation("jobScheduler stoped.");
        }


        private ITrigger CreateTrigger(string name, string cronExpression)
        {
            return TriggerBuilder
                .Create()
                .WithIdentity($"{name}.trigger")
                .WithCronSchedule(cronExpression)
                .Build();
        }

        private IJobDetail CreateJob(Type jobType)
        {
            return JobBuilder
                .Create(jobType)
                .WithIdentity(jobType.FullName)
                .WithDescription(jobType.Name)
                .Build();
        }
    }
}
